
package com.eltonkent.db;

import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

final class DBSetupWizard extends SQLiteOpenHelper
{

	public DBSetupWizard(Context context, String name, CursorFactory factory, int version)
	{
		super(context, name, factory, version);
	}

	private void createTable(SQLiteDatabase sqlitedatabase, GenericTable tableClass)
	{
		StringBuilder sql = new StringBuilder("CREATE TABLE " + tableClass.getTableName() + "(");
		List<Field> columns = tableClass.getTableFields();
		for(int i = 0; i < columns.size() - 1; i++)
		{
			sql.append(columns.get(i));
			sql.append(',');
		}
		sql.append(columns.get(columns.size() - 1));
		sql.append(");");
		Log.d("DB", "Create table Query " + sql);
		sqlitedatabase.execSQL(sql.toString());
		tableClass.doAfterTableCreate(sqlitedatabase);
	}

	@Override
	public void onCreate(SQLiteDatabase sqlitedatabase)
	{
		createTable(sqlitedatabase, new CredentialTable());
		createTable(sqlitedatabase, new FolderListTable());
		createTable(sqlitedatabase, new SafeEntryTable());
		createTable(sqlitedatabase, new CustomTemplateTable());
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqlitedatabase, int i, int j)
	{
		sqlitedatabase.execSQL("DROP TABLE IF EXISTS " + CredentialTable.TABLE_NAME);
		sqlitedatabase.execSQL("DROP TABLE IF EXISTS " + FolderListTable.TABLE_NAME);
		sqlitedatabase.execSQL("DROP TABLE IF EXISTS " + SafeEntryTable.TABLE_NAME);
		onCreate(sqlitedatabase);
	}
}
